import { Config } from './config.js';
import { Token } from './token.js';
import { hexMD5 } from './md5.js';

var CryptoJS = require('./public.js');

class Base {
    constructor() {
        //构造函数
        this.baseRequestUrl = Config.resUrl;
        this._loading = false; //定义一个变量来判断是否loading
    }

    apiRequest(params, eCallback, noRefech = false) {
        var that = this;
        var url = this.baseRequestUrl + params.url;
        var kAppKey = 'wxmini',
            kAppSecret = 'xjml415ds5a';
        var timestamp = Date.parse(new Date());
        timestamp = CryptoJS.encrypt(timestamp / 1000); //console.log( CryptoJS.decrypt(timestamp));

        var randomstr = that._randomStr();

        var obj = params.data ? params.data : {};
        obj.timestamp = timestamp;
        obj.randomstr = randomstr;
        var sign = this.signature(obj, kAppKey, kAppSecret);

        if (!params.type) {
            params.type = 'GET';
        }

        if (params.loading) {
            uni.showLoading({
                title: '加载中',
                // 数据请求前loading
                mask: true
            });
        }

        uni.request({
            url: url,
            data: params.data,
            header: {
				minicode:'ummC5xOU74UoVrOoSnm4gaXTUhPjIn3wPYVRkfUI1bqKf5VrC0',
                'content-type': 'application/json',
                token: uni.getStorageSync('token'),
                sign: sign,
                randomstr: randomstr,
                timestamp: timestamp,
                identity: uni.getStorageSync('identity')
            },
            method: params.type,
            dataType: 'json',
            responseType: 'text',
            success: function (res) {
                // console.log(res);
                var code = res.statusCode.toString();
                var startChar = code.charAt(0);

                if (startChar == '2') {
                    if (params.loading) {
                        uni.hideLoading();
                    }

                    eCallback && eCallback(res.data);
                } else {
                    if (code == '401') {
						uni.showToast({
							title:'请先登录',
							icon:'none'
						})
						setTimeout(() => {
							uni.navigateTo({
								url:"/pages/login/login"
							})
						},1000)
					
                    }

                    if (code == '402') {
                        uni.setStorageSync('shop_user', '');
                        uni.setStorageSync('identity', '');
                        uni.navigateTo({
							url:"/pages/login/login"
                       })
                    }

                    if (noRefech) {
                        eCallback && eCallback(res.data);
                    }
                } // if(params.sCallBack){
                //   params.sCallBack(res);
                // }
                //等同于上面if,
                //params.sCallback && params.sCallback(res.data);
            },
            fail: function (res) {
                if (params.loading) {
                    uni.hideLoading();
                }
            },
            complete: function (res) {}
        });
    }

    _refetch(param, eCallback) {
        var token = new Token();
        token.getTokenFromServer((token) => {
            this.apiRequest(param, eCallback, true);
        });
    }

    _randomStr() {
        var arr = [
            'a',
            'b',
            'c',
            'd',
            'e',
            'f',
            'h',
            'i',
            'j',
            'k',
            'l',
            'm',
            'n',
            'o',
            'p',
            'q',
            'w',
            'v',
            'u',
            'r',
            's',
            't',
            'x',
            'y',
            'z',
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            '0'
        ];
        var str = '';

        for (var i = 0; i < 12; i++) {
            var inx = parseInt(Math.random() * (arr.length - 1));

            if (inx < arr.length) {
                str += arr[inx];
            }
        }

        return str;
    } //签名

    signature(data, kAppKey, key) {
        var n = null,
            d = {},
            str = '',
            s = '';
        data.appKey = kAppKey;
        data.timestamp = '';
        n = Object.keys(data).sort();

        for (var i in n) {
            d[n[i]] = data[n[i]];
        }

        var that = this;

        for (var k in d) {
            if (d[k] === '') continue;
            if (str != '') str += '&';
            str += k + '=' + encodeURI(d[k]);
        }

        str += '&key=' + key;
        s = hexMD5(str).toUpperCase(); // 这儿是进行MD5加密并转大写

        return str;
    }

    setNewVal(str) {
        if (typeof str == 'string') {
            //替换字符串中的所有特殊字符（包含空格）
            if (str != '') {
                var pattern = /[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g;
                return str.replace(pattern, '');
            }
        }
    }

    getSign(params, kAppKey, kAppSecret) {
        if (typeof params == 'string') {
            return this.paramsStrSort(params, kAppKey, kAppSecret);
        } else if (typeof params == 'object') {
            var arr = [];

            for (var i in params) {
                var str = params[i];

                if (!/^[a-zA-Z0-9_]{0,}$/.test(str)) {
                    str = encodeURIComponent(str);
                }

                arr.push(i + '=' + str);
            }

            return this.paramsStrSort(arr.join('&'), kAppKey, kAppSecret);
        }
    }

    paramsStrSort(paramsStr, kAppKey, kAppSecret) {
        var url = paramsStr + '&appKey=' + kAppKey;
        var urlStr = url.split('&').sort().join('&');
        var newUrl = urlStr + '&key=' + kAppSecret;
        return hexMD5(newUrl).toUpperCase();
    }

    upload(res, eCallback,category='') {
        var timestamp = Date.parse(new Date());
        timestamp = CryptoJS.encrypt(timestamp / 1000);
        uni.showLoading({
            title: '上传中',
            mask: true
        });
        uni.uploadFile({
            url: Config.baseUrl + 'common/upload',
            filePath: res,
            name: 'file',
            header: {
                // 'content-type': 'application/json',
                timestamp: timestamp,
                token: uni.getStorageSync('token'),
				category:category
            },
           success: function (res) {
				uni.hideLoading();
               var code = res.statusCode.toString();
               var startChar = code.charAt(0);
           
               if (startChar == '2') {
                   eCallback && eCallback(res.data);
               } else {
                   if (code == '401') {
           			uni.showToast({
           				title:'请先登录',
           				icon:'none'
           			})
           			setTimeout(() => {
           				uni.navigateTo({	
           								
           					url:"/pages/login/login"
           				})
           			},800)
           		
                   }
           
                   if (code == '402') {
                       uni.setStorageSync('shop_user', '');
                       uni.setStorageSync('identity', '');
                       uni.navigateTo({
           				url:"/pages/login/login"
                      })
                   }
           
            
               } // if(params.sCallBack){
               //   params.sCallBack(res);
               // }
               //等同于上面if,
               //params.sCallback && params.sCallback(res.data);
           },
           
            fail: function (data) {
                console.log(data);
                uni.hideLoading({
                    complete: (res) => {}
                });
                uni.showToast({
                    title: '上传失败',
                    icon: 'none'
                });
            }
        });
    }

    myLogin(page, e, options = {}) {
        var that = this;
        uni.getUserProfile({
            desc: '用于完善会员资料',
            // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                uni.login({
                    success(r) {
                        if (r.code) {
                            var pid = 0;
                            var store_id = 0;

                            if (uni.getStorageSync('pid')) {
                                pid = uni.getStorageSync('pid');
                            }

                            if (page.data.share_store_id) {
                                store_id = page.data.share_store_id;
                            }

                            that.apiRequest(
                                {
                                    url: 'user/wxLogin',
                                    type: 'POST',
                                    data: {
                                        code: r.code,
                                        avatarUrl: res.userInfo.avatarUrl,
                                        nickName: res.userInfo.nickName,
                                        gender: res.userInfo.gender,
                                        pid: pid,
                                        store_id: store_id
                                    }
                                },
                                (ret) => {
                                    if (ret.code == 1) {
                                        uni.setStorageSync('userinfo', ret.data);
                                        uni.setStorageSync('token', ret.data.token);
                                        page.setData({
                                            showAuthView: false
                                        });
                                        page.onLoad(options);
                                        page.onShow(options);
                                    } else {
                                        uni.showModal({
                                            title: '提示',
                                            content: '授权失败',
                                            showCancel: false
                                        });
                                    }
                                }
                            );
                        } else {
                            console.log('登录失败！' + res.errMsg);
                        }
                    }
                });
            }
        });
    }
}

export { Base };
